<template>
  <div class="finance-manage">
    <div class="page-header">
      <h2>财务管理</h2>
      <el-button-group>
        <el-button @click="getFinanceList">刷新列表</el-button>
        <el-select v-model="filterStatus" placeholder="结算状态" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="待结算" value="pending" />
          <el-option label="已结算" value="settled" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </el-button-group>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>待结算总额</span>
                <el-tag type="warning">待处理</el-tag>
              </div>
            </template>
            <div class="card-amount">
              <span class="amount">¥ {{ formatAmount(statistics.pendingAmount) }}</span>
              <span class="count">{{ statistics.pendingCount }} 笔</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>本月已结算</span>
                <el-tag type="success">已完成</el-tag>
              </div>
            </template>
            <div class="card-amount">
              <span class="amount">¥ {{ formatAmount(statistics.monthSettled) }}</span>
              <span class="count">{{ statistics.monthCount }} 笔</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>累计结算金额</span>
                <el-tag type="info">总计</el-tag>
              </div>
            </template>
            <div class="card-amount">
              <span class="amount">¥ {{ formatAmount(statistics.totalAmount) }}</span>
              <span class="count">{{ statistics.totalCount }} 笔</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 结算列表 -->
    <el-card v-loading="loading" class="list-card">
      <el-table :data="financeList" style="width: 100%">
        <el-table-column prop="id" label="结算ID" width="100" />
        <el-table-column prop="businessName" label="商家名称" width="180" show-overflow-tooltip />
        <el-table-column prop="period" label="结算周期" width="240">
          <template #default="{ row }">
            {{ formatDate(row.startDate) }} 至 {{ formatDate(row.endDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderCount" label="订单数" width="100" align="right" />
        <el-table-column prop="totalAmount" label="结算金额" width="150" align="right">
          <template #default="{ row }">
            ¥ {{ formatAmount(row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="commission" label="平台佣金" width="150" align="right">
          <template #default="{ row }">
            ¥ {{ formatAmount(row.commission) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="实际金额" width="150" align="right">
          <template #default="{ row }">
            ¥ {{ formatAmount(row.actualAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
                type="primary"
                link
                @click="handleViewDetails(row)"
            >
              查看详情
            </el-button>
            <el-button
                v-if="row.status === 'pending'"
                type="success"
                link
                @click="handleSettle(row)"
            >
              确认结算
            </el-button>
            <el-button
                v-if="row.status === 'pending'"
                type="danger"
                link
                @click="handleCancel(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 结算详情对话框 -->
    <el-dialog
        v-model="detailsDialogVisible"
        title="结算详情"
        width="800px"
    >
      <div class="settlement-details" v-if="currentSettlement">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="结算ID">{{ currentSettlement.id }}</el-descriptions-item>
          <el-descriptions-item label="商家名称">{{ currentSettlement.businessName }}</el-descriptions-item>
          <el-descriptions-item label="结算周期" :span="2">
            {{ formatDate(currentSettlement.startDate) }} 至 {{ formatDate(currentSettlement.endDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="订单数量">{{ currentSettlement.orderCount }}</el-descriptions-item>
          <el-descriptions-item label="结算状态">
            <el-tag :type="getStatusType(currentSettlement.status)">
              {{ getStatusText(currentSettlement.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总金额">¥ {{ formatAmount(currentSettlement.totalAmount) }}</el-descriptions-item>
          <el-descriptions-item label="平台佣金">¥ {{ formatAmount(currentSettlement.commission) }}</el-descriptions-item>
          <el-descriptions-item label="实际结算">¥ {{ formatAmount(currentSettlement.actualAmount) }}</el-descriptions-item>
          <el-descriptions-item label="结算时间" v-if="currentSettlement.settleTime">
            {{ formatDate(currentSettlement.settleTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2" v-if="currentSettlement.remark">
            {{ currentSettlement.remark }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="order-list">
          <h3>订单明细</h3>
          <el-table :data="currentSettlement.orders" style="width: 100%">
            <el-table-column prop="orderNo" label="订单编号" width="180" />
            <el-table-column prop="productName" label="商品名称" show-overflow-tooltip />
            <el-table-column prop="quantity" label="数量" width="80" align="right" />
            <el-table-column prop="amount" label="金额" width="120" align="right">
              <template #default="{ row }">
                ¥ {{ formatAmount(row.amount) }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 结算确认对话框 -->
    <el-dialog
        v-model="settleDialogVisible"
        title="确认结算"
        width="500px"
    >
      <div class="settle-confirm" v-if="currentSettlement">
        <el-alert
            title="请确认以下结算信息"
            type="warning"
            :closable="false"
            class="settle-alert"
        />
        <div class="settle-info">
          <p><strong>商家名称：</strong>{{ currentSettlement.businessName }}</p>
          <p><strong>结算周期：</strong>{{ formatDate(currentSettlement.startDate) }} 至 {{ formatDate(currentSettlement.endDate) }}</p>
          <p><strong>订单数量：</strong>{{ currentSettlement.orderCount }} 笔</p>
          <p><strong>结算金额：</strong>¥ {{ formatAmount(currentSettlement.actualAmount) }}</p>
        </div>
        <el-form
            ref="settleFormRef"
            :model="settleForm"
            :rules="settleRules"
            label-width="80px"
        >
          <el-form-item label="备注" prop="remark">
            <el-input
                v-model="settleForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入结算备注（选填）"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="settleDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitSettle">
            确认结算
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const submitting = ref(false)
const detailsDialogVisible = ref(false)
const settleDialogVisible = ref(false)
const currentSettlement = ref(null)
const financeList = ref([])
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const statistics = ref({
  pendingAmount: 0,
  pendingCount: 0,
  monthSettled: 0,
  monthCount: 0,
  totalAmount: 0,
  totalCount: 0
})

const settleForm = ref({
  remark: ''
})

const settleRules = {
  remark: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 获取财务统计
const getStatistics = async () => {
  try {
    const response = await request({
      url: '/v1/admin/finance/statistics',
      method: 'get'
    })
    if (response.code === 2000) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取财务统计失败:', error)
    ElMessage.error('获取财务统计失败')
  }
}

// 获取结算列表
const getFinanceList = async () => {
  loading.value = true
  try {
    const response = await request({
      url: '/v1/admin/finance/list',
      method: 'get',
      params: {
        status: filterStatus.value,
        page: currentPage.value,
        size: pageSize.value
      }
    })
    if (response.code === 2000) {
      financeList.value = response.data.list
      total.value = response.data.total
    }
  } catch (error) {
    console.error('获取结算列表失败:', error)
    ElMessage.error('获取结算列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化金额
const formatAmount = (amount) => {
  return Number(amount).toFixed(2)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'settled': 'success',
    'cancelled': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待结算',
    'settled': '已结算',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 查看结算详情
const handleViewDetails = async (row) => {
  try {
    const response = await request({
      url: `/v1/admin/finance/detail/${row.id}`,
      method: 'get'
    })
    if (response.code === 2000) {
      currentSettlement.value = response.data
      detailsDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取结算详情失败:', error)
    ElMessage.error('获取结算详情失败')
  }
}

// 打开结算确认对话框
const handleSettle = (row) => {
  currentSettlement.value = row
  settleForm.value.remark = ''
  settleDialogVisible.value = true
}

// 提交结算
const submitSettle = async () => {
  if (!currentSettlement.value) return

  submitting.value = true
  try {
    const response = await request({
      url: `/v1/admin/finance/settle/${currentSettlement.value.id}`,
      method: 'post',
      data: settleForm.value
    })
    if (response.code === 2000) {
      ElMessage.success('结算成功')
      settleDialogVisible.value = false
      getFinanceList()
      getStatistics()
    }
  } catch (error) {
    console.error('结算失败:', error)
    ElMessage.error('结算失败')
  } finally {
    submitting.value = false
  }
}

// 取消结算
const handleCancel = (row) => {
  ElMessageBox.confirm(
      '确定要取消该笔结算吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      const response = await request({
        url: `/v1/admin/finance/cancel/${row.id}`,
        method: 'post'
      })
      if (response.code === 2000) {
        ElMessage.success('取消结算成功')
        getFinanceList()
        getStatistics()
      }
    } catch (error) {
      console.error('取消结算失败:', error)
      ElMessage.error('取消结算失败')
    }
  }).catch(() => {})
}

// 处理筛选状态变化
const handleFilterChange = () => {
  currentPage.value = 1
  getFinanceList()
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getFinanceList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getFinanceList()
}

onMounted(() => {
  getStatistics()
  getFinanceList()
})
</script>

<style scoped>
.finance-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-amount {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.card-amount .amount {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.card-amount .count {
  font-size: 14px;
  color: #909399;
}

.list-card {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.settlement-details {
  padding: 0 20px;
}

.order-list {
  margin-top: 20px;
}

.order-list h3 {
  margin: 0 0 15px 0;
  color: #606266;
}

.settle-confirm {
  padding: 0 20px;
}

.settle-alert {
  margin-bottom: 20px;
}

.settle-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.settle-info p {
  margin: 8px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-select) {
  margin-left: 10px;
  width: 120px;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}
</style>